package com.alvis.media.controller;

import com.alvis.media.base.BaseApiController;
import com.alvis.media.base.NonStaticResourceHttpRequestHandler;
import com.alvis.media.base.RestResponse;
import com.alvis.media.domain.*;
import com.alvis.media.service.VideoInfoService;
import com.alvis.media.utility.PageInfoHelper;
import com.alvis.media.viewmodel.video.*;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController("VideoController")
@RequestMapping(value = "/api/admin/video")
@AllArgsConstructor
public class VideoController  extends BaseApiController {

    private  final VideoInfoService videoInfoService;

    @Autowired
    private NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    @GetMapping("/play/**/*")
    public void playVideo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //realPath 即视频所在的完整地址
        String url = request.getRequestURL().toString();
        int index = url.lastIndexOf("/api/admin/video/play/");
        if (index != -1) {
            String realPath = url.substring(index + "/api/admin/video/play/".length());
            // 如果路径以"D:"开头，则直接使用该路径
            if (realPath.startsWith("D:")) {
                // 路径已经是完整的
            } else {
                // 否则需要添加基础路径前缀
                realPath = "D:/" + realPath;
            }

            Path filePath = Paths.get(realPath);
            if (Files.exists(filePath)) {
                // 利用 Files.probeContentType 获取文件类型
                String mimeType = Files.probeContentType(filePath);
                if (!StringUtils.isEmpty(mimeType)) {
                    // 设置 response
                    response.setContentType(mimeType);
                }
                request.setAttribute(nonStaticResourceHttpRequestHandler.filepath, filePath);
                // 利用 ResourceHttpRequestHandler.handlerRequest() 实现返回视频流
                nonStaticResourceHttpRequestHandler.handleRequest(request, response);
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            }
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> select(@PathVariable Integer id) {
        VideoInfo video = videoInfoService.selectById(id);
        videoInfoService.insertVideoPlay(video.getVideoUrl(), getCurrentUser().getId());
        video.setVideoUrl("/api/admin/video/play/"+video.getVideoUrl());
        VideoResponseVM videoVm = VideoResponseVM.from(video);
        return RestResponse.ok(videoVm);
    }

    /**
     * 根据视频ID查询视频详细信息
     * @param id   视频ID
     * @return RestResponse<VideoDetailVM>  视频的详情VM
     */
    @RequestMapping(value = "/getVideoDetailByVideoId/{id}", method = RequestMethod.POST)
    public RestResponse<VideoDetailVM> getVideoDetailByVideoId(@PathVariable Integer id)
    {
        VideoInfo video = videoInfoService.selectById(id);

        VideoDetailVM vm = new VideoDetailVM();
        vm.setVideoId(video.getVideoId());
        vm.setVideoName(video.getVideoName());

        List<VideoPlay> videoPlayList = new ArrayList<VideoPlay>();
        VideoPlay videoPlay = new VideoPlay();
        videoPlay.setVideoName("用户" + getCurrentUser().getUserName() + "于 " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "播放了视频: " + video.getVideoName());
        videoPlayList.add(videoPlay);

        // 视频推荐列表
        List<VideoInfo> videoRecommendList = videoInfoService.userAnalysis(getCurrentUser().getId());
        vm.setVideoRecommendList(videoRecommendList);

        List <UserVideoOperation> videoOperationList = new ArrayList<UserVideoOperation>();

        List<UserTag> videoTagList = new ArrayList<UserTag>();
        vm.setVideoPlayList(videoPlayList);
        vm.setVideoOperationList(videoOperationList);
        vm.setVideoTagList(videoTagList);

        return RestResponse.ok(vm);
    }

    @RequestMapping(value = "/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo <VideoResponseVM>> pageList(@RequestBody VideoPageRequestVM model) {
        PageInfo<VideoInfo> pageInfo = videoInfoService.userPage(model);
        PageInfo<VideoResponseVM> page = PageInfoHelper.copyMap(pageInfo, d -> VideoResponseVM.from(d));
        return RestResponse.ok(page);
    }

    /**
     * 视频创建
     * @param model
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> createVideo(@RequestBody @Valid VideoCreateVM model)
    {
        // step1 校验视频是否上传 （判断url是否为空）
        if(StringUtils.isBlank(model.getVideoUrl()))
        {
            return RestResponse.fail(500,"视频文件未上传");
        }

        // 前端VideoCreateVM对象映射为数据库实体VideoInfo
        VideoInfo video = modelMapper.map(model,VideoInfo.class);

        User user = getCurrentUser();     // 获取当前用户
        video.setCreatorId(user.getId()); // 设置上传视频的作者ID
        video.setCreateTime(new Date());  // 设置创建时间
        video.setLastModifyTime(new Date()); // 设置最后修改时间

        // step2 调用service层做入库操作
        videoInfoService.insertByFilter(video);

        // 返回视频响应VM
        VideoResponseVM videoResponseVM = VideoResponseVM.from(video);
        return RestResponse.ok(videoResponseVM);
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> editVideo(@RequestBody @Valid VideoCreateVM model) {
        // 校验视频ID是否存在
        if (model.getVideoId() == null) {
            return RestResponse.fail(500, "视频ID不能为空");
        }
        
        // 校验视频名称是否为空
        if (StringUtils.isBlank(model.getVideoName())) {
            return RestResponse.fail(500, "视频名称不能为空");
        }

        // 根据视频ID查询视频信息
        VideoInfo video = videoInfoService.selectById(model.getVideoId());
        if (video == null) {
            return RestResponse.fail(500, "视频不存在");
        }

        // 更新视频信息
        video.setVideoName(model.getVideoName());
        video.setVideoCategory(model.getVideoCategory());
        // 只有当新的视频URL不为空时才更新URL（允许用户只修改名称或分类而不重新上传文件）
        if (StringUtils.isNotBlank(model.getVideoUrl())) {
            video.setVideoUrl(model.getVideoUrl());
        }
        video.setLastModifyTime(new Date());
        
        // 调用service层更新视频信息
        videoInfoService.updateByIdFilter(video);

        // 构造返回结果
        VideoResponseVM videoResponseVM = VideoResponseVM.from(video);
        return RestResponse.ok(videoResponseVM);
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        // 根据视频ID删除视频信息
        videoInfoService.deleteById(id);
        return RestResponse.ok();
    }

    @RequestMapping(value = "/userAnalysis/{id}", method = RequestMethod.POST)
    public RestResponse <UserAnalysisVM> userAnalysis(@PathVariable Integer id) {
        List<VideoInfo> recommendVideoList = videoInfoService.userAnalysis(id);
        UserAnalysisVM vm = new UserAnalysisVM();
        vm.setVideoRecommendList(recommendVideoList);
        return RestResponse.ok(vm);
    }
}